import Vue from 'vue'
import VueRouter from 'vue-router'
import Preview from "@/components/CKEditor5/preview";
import Login from '../views/Login.vue'
import Store from '@/store'

Vue.use(VueRouter)

//以下代码解决路由地址重复的报错问题
const originalReplace = VueRouter.prototype.replace;
   VueRouter.prototype.replace = function replace(location) {
   return originalReplace.call(this, location).catch(err => err);
};

const createRouter = () => new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/login',
      component: Login,
      name: '登录页面'
    }
  ]
})

const router = createRouter()

//挂载路由导航守卫
//to 将要访问路径
//from 从哪个路径跳转而来
//next 放行函数
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    return next();
  }
  //验证Token
  if (!Store.state.user.token) {
    Store.dispatch('ClearStore');
    return next('/login');
  }
  return next();
});

export default router
